<template>
  <div class="farmer-product-management">
    <!-- 头部操作栏 -->
    <div class="header-section">
      <div class="header-actions">
        <el-button type="primary" @click="handleAddProduct" class="add-btn">
          <el-icon><Plus /></el-icon>
          添加农产品
        </el-button>
        <el-button type="success" @click="handleAddPromotion" class="promotion-btn">
          <el-icon><Discount /></el-icon>
          添加促销产品
        </el-button>
      </div>
    </div>

    <!-- 筛选和搜索 -->
    <div class="filter-section">
      <el-card class="filter-card">
        <div class="filter-content">
          <div class="filter-left">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索农产品名称..."
              prefix-icon="Search"
              clearable
              style="width: 300px;"
              @clear="handleSearch"
              @keyup.enter="handleSearch"
            />
            <el-select
              v-model="filterStatus"
              placeholder="全部状态"
              clearable
              style="width: 150px; margin-left: 12px;"
              @change="handleFilter"
            >
              <el-option label="全部状态" value="" />
              <el-option label="上架中" value="1" />
              <el-option label="已下架" value="0" />
            </el-select>
            <el-select
              v-model="filterType"
              placeholder="全部类型"
              clearable
              style="width: 150px; margin-left: 12px;"
              @change="handleFilter"
            >
              <el-option label="全部类型" value="" />
              <el-option label="普通产品" value="normal" />
              <el-option label="促销产品" value="promotion" />
            </el-select>
          </div>
          <div class="filter-right">
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 产品列表 -->
    <div class="product-list-section">
      <el-card class="product-list-card">
        <template #header>
          <div class="list-header">
            <span class="list-title">产品列表</span>
            <span class="list-count">共 {{ total }} 个产品</span>
          </div>
        </template>

        <el-table
          :data="productList"
          v-loading="loading"
          style="width: 100%"
          row-key="id"
          :default-sort="{ prop: 'createTime', order: 'descending' }"
        >
          <el-table-column label="产品图片" width="100" align="center">
            <template #default="{ row }">
              <el-avatar
                :size="60"
                :src="row.productImage"
                fit="cover"
                shape="square"
                class="product-image"
              >
                <template #error>
                  <div class="image-error">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-avatar>
            </template>
          </el-table-column>

          <el-table-column prop="productName" label="产品名称" min-width="180">
            <template #default="{ row }">
              <div class="product-name">
                <span class="name-text">{{ row.productName }}</span>
                <el-tag
                  v-if="row.isPromotion"
                  type="danger"
                  size="small"
                  effect="light"
                  class="promotion-tag"
                >
                  促销
                </el-tag>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="价格信息" min-width="180">
            <template #default="{ row }">
              <div class="price-info">
                <template v-if="row.isPromotion">
                  <div class="original-price">¥{{ row.originalPrice }}</div>
                  <div class="current-price">¥{{ row.currentPrice }}</div>
                  <div class="discount-rate">
                    省{{ calculateDiscount(row.originalPrice, row.currentPrice) }}
                  </div>
                </template>
                <template v-else>
                  <div class="normal-price">¥{{ row.marketPrice }}</div>
                </template>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="productDescription" label="产品描述" min-width="200" show-overflow-tooltip />

          <el-table-column label="状态" width="100" align="center">
            <template #default="{ row }">
              <el-tag
                :type="row.status === 1 ? 'success' : 'info'"
                effect="light"
              >
                {{ row.status === 1 ? '上架' : '下架' }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="createTime" label="创建时间" width="180" sortable>
            <template #default="{ row }">
              {{ formatDate(row.createTime) }}
            </template>
          </el-table-column>

          <el-table-column label="操作" width="200" fixed="right" align="center">
            <template #default="{ row }">
              <div class="action-buttons">
                <el-button
                  type="primary"
                  link
                  size="small"
                  @click="handleEdit(row)"
                >
                  <el-icon><Edit /></el-icon>
                  编辑
                </el-button>
                <el-button
                  :type="row.status === 1 ? 'warning' : 'success'"
                  link
                  size="small"
                  @click="handleToggleStatus(row)"
                >
                  <el-icon v-if="row.status === 1"><Remove /></el-icon>
                  <el-icon v-else><CircleCheck /></el-icon>
                  {{ row.status === 1 ? '下架' : '上架' }}
                </el-button>
                <el-button
                  type="danger"
                  link
                  size="small"
                  @click="handleDelete(row)"
                >
                  <el-icon><Delete /></el-icon>
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-section">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 添加/编辑产品对话框 -->
    <el-dialog
      v-model="showProductDialog"
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
      class="product-dialog"
    >
      <el-form
        ref="productFormRef"
        :model="productForm"
        :rules="productRules"
        label-width="100px"
        class="product-form"
      >
        <el-form-item label="产品类型" prop="isPromotion">
          <el-radio-group v-model="productForm.isPromotion">
            <el-radio :label="false">普通产品</el-radio>
            <el-radio :label="true">促销产品</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="产品名称" prop="productName">
          <el-input
            v-model="productForm.productName"
            placeholder="请输入产品名称"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>

        <el-form-item v-if="!productForm.isPromotion" label="市场价格" prop="marketPrice">
          <el-input-number
            v-model="productForm.marketPrice"
            placeholder="请输入市场价格"
            :min="0"
            :precision="2"
            :step="0.1"
            style="width: 200px;"
          />
          <span class="unit">元</span>
        </el-form-item>

        <template v-else>
          <el-form-item label="原价格" prop="originalPrice">
            <el-input-number
              v-model="productForm.originalPrice"
              placeholder="请输入原价格"
              :min="0"
              :precision="2"
              :step="0.1"
              style="width: 200px;"
            />
            <span class="unit">元</span>
          </el-form-item>
          <el-form-item label="现价格" prop="currentPrice">
            <el-input-number
              v-model="productForm.currentPrice"
              placeholder="请输入现价格"
              :min="0"
              :precision="2"
              :step="0.1"
              style="width: 200px;"
            />
            <span class="unit">元</span>
            <div class="price-tips" v-if="productForm.originalPrice && productForm.currentPrice">
              <el-tag
                :type="productForm.currentPrice < productForm.originalPrice ? 'success' : 'warning'"
                size="small"
              >
                优惠 {{ calculateDiscount(productForm.originalPrice, productForm.currentPrice) }}
              </el-tag>
            </div>
          </el-form-item>
        </template>

        <el-form-item label="产品描述" prop="productDescription">
          <el-input
            v-model="productForm.productDescription"
            type="textarea"
            :rows="4"
            placeholder="请输入产品描述"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="产品图片" prop="productImage">
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :before-upload="beforeImageUpload"
            :http-request="handleImageUpload"
            accept="image/jpeg,image/png,image/gif,image/webp"
          >
            <img v-if="productForm.productImage" :src="productForm.productImage" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tips">
            支持 JPG、PNG、GIF、WEBP 格式，大小不超过 2MB，建议尺寸 400x400 像素
          </div>
        </el-form-item>

        <el-form-item label="产品状态" prop="status">
          <el-radio-group v-model="productForm.status">
            <el-radio :label="1">上架</el-radio>
            <el-radio :label="0">下架</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showProductDialog = false" size="large">取消</el-button>
        <el-button
          type="primary"
          @click="handleSubmit"
          :loading="submitting"
          size="large"
        >
          {{ isEditing ? '更新' : '创建' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import {
  Plus, Discount, Search, Refresh, Picture,
  Edit, Remove, CircleCheck, Delete
} from '@element-plus/icons-vue'

// 路由
const router = useRouter()

// 响应式数据
const loading = ref(false)
const showProductDialog = ref(false)
const submitting = ref(false)
const isEditing = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const searchKeyword = ref('')
const filterStatus = ref('')
const filterType = ref('')

const productFormRef = ref(null)

const user = ref({
  name: '张大山',
  role: '认证农夫',
  avatar: 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?ixlib=rb-1.2.1&auto=format&fit=crop&w=100&q=80'
})

const userLocation = ref('北京, 顺义区')

// 产品列表数据
const productList = ref([
  {
    id: 1,
    productName: '有机西红柿',
    marketPrice: 8.5,
    productDescription: '新鲜有机西红柿，无农药残留，口感鲜美',
    productImage: 'https://images.unsplash.com/photo-1546470427-e212b7d31075?w=400&h=400&fit=crop',
    status: 1,
    isPromotion: false,
    createTime: '2024-01-15T10:00:00Z'
  },
  {
    id: 2,
    productName: '特价土鸡蛋',
    originalPrice: 25.0,
    currentPrice: 18.8,
    productDescription: '农家散养土鸡蛋，营养丰富，限时特价',
    productImage: 'https://images.unsplash.com/photo-1582722872445-44dc5f7e3c8f?w=400&h=400&fit=crop',
    status: 1,
    isPromotion: true,
    createTime: '2024-01-14T15:30:00Z'
  },
  {
    id: 3,
    productName: '新鲜黄瓜',
    marketPrice: 6.0,
    productDescription: '当天采摘新鲜黄瓜，清脆爽口',
    productImage: 'https://images.unsplash.com/photo-1449300079327-02f967c1c1e7?w=400&h=400&fit=crop',
    status: 0,
    isPromotion: false,
    createTime: '2024-01-13T09:20:00Z'
  }
])

// 产品表单数据
const productForm = reactive({
  id: null,
  productName: '',
  marketPrice: null,
  originalPrice: null,
  currentPrice: null,
  productDescription: '',
  productImage: '',
  status: 1,
  isPromotion: false
})

// 表单验证规则
const productRules = {
  productName: [
    { required: true, message: '请输入产品名称', trigger: 'blur' },
    { min: 2, max: 50, message: '产品名称长度为2-50个字符', trigger: 'blur' }
  ],
  marketPrice: [
    { 
      required: true, 
      message: '请输入市场价格', 
      trigger: 'blur',
      validator: (rule, value, callback) => {
        if (!productForm.isPromotion && (value === null || value === '')) {
          callback(new Error('请输入市场价格'))
        } else {
          callback()
        }
      }
    }
  ],
  originalPrice: [
    { 
      required: true, 
      message: '请输入原价格', 
      trigger: 'blur',
      validator: (rule, value, callback) => {
        if (productForm.isPromotion && (value === null || value === '')) {
          callback(new Error('请输入原价格'))
        } else {
          callback()
        }
      }
    }
  ],
  currentPrice: [
    { 
      required: true, 
      message: '请输入现价格', 
      trigger: 'blur',
      validator: (rule, value, callback) => {
        if (productForm.isPromotion && (value === null || value === '')) {
          callback(new Error('请输入现价格'))
        } else {
          callback()
        }
      }
    },
    {
      validator: (rule, value, callback) => {
        if (productForm.isPromotion && productForm.originalPrice && value > productForm.originalPrice) {
          callback(new Error('现价格不能高于原价格'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  productDescription: [
    { required: true, message: '请输入产品描述', trigger: 'blur' },
    { min: 10, max: 200, message: '产品描述长度为10-200个字符', trigger: 'blur' }
  ],
  productImage: [
    { required: true, message: '请上传产品图片', trigger: 'change' }
  ]
}

// 计算属性
const dialogTitle = computed(() => {
  return isEditing.value ? '编辑产品' : (productForm.isPromotion ? '添加促销产品' : '添加农产品')
})

// 方法
const formatDate = (dateString) => {
  if (!dateString) return ''
  return new Date(dateString).toLocaleString('zh-CN')
}

const calculateDiscount = (originalPrice, currentPrice) => {
  if (!originalPrice || !currentPrice) return '0%'
  const discount = ((originalPrice - currentPrice) / originalPrice * 100).toFixed(1)
  return `${discount}%`
}

const handleSearch = () => {
  currentPage.value = 1
  loadProductList()
}

const handleReset = () => {
  searchKeyword.value = ''
  filterStatus.value = ''
  filterType.value = ''
  currentPage.value = 1
  loadProductList()
}

const handleFilter = () => {
  currentPage.value = 1
  loadProductList()
}

const handleSizeChange = (size) => {
  pageSize.value = size
  loadProductList()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  loadProductList()
}

const handleAddProduct = () => {
  isEditing.value = false
  resetProductForm()
  productForm.isPromotion = false
  showProductDialog.value = true
}

const handleAddPromotion = () => {
  isEditing.value = false
  resetProductForm()
  productForm.isPromotion = true
  showProductDialog.value = true
}

const handleEdit = (row) => {
  isEditing.value = true
  Object.assign(productForm, {
    id: row.id,
    productName: row.productName,
    marketPrice: row.marketPrice,
    originalPrice: row.originalPrice,
    currentPrice: row.currentPrice,
    productDescription: row.productDescription,
    productImage: row.productImage,
    status: row.status,
    isPromotion: row.isPromotion
  })
  showProductDialog.value = true
}

const handleToggleStatus = async (row) => {
  try {
    const newStatus = row.status === 1 ? 0 : 1
    const action = newStatus === 1 ? '上架' : '下架'
    
    await ElMessageBox.confirm(
      `确定要${action}产品"${row.productName}"吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 模拟API调用
    row.status = newStatus
    ElMessage.success(`产品已${action}`)
  } catch (error) {
    // 用户取消操作
  }
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除产品"${row.productName}"吗？此操作不可恢复。`,
      '警告',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'error',
        confirmButtonClass: 'el-button--danger'
      }
    )
    
    // 模拟API调用
    productList.value = productList.value.filter(item => item.id !== row.id)
    ElMessage.success('产品删除成功')
  } catch (error) {
    // 用户取消操作
  }
}

const handleSubmit = async () => {
  if (!productFormRef.value) return
  
  try {
    await productFormRef.value.validate()
    submitting.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    if (isEditing.value) {
      // 更新产品
      const index = productList.value.findIndex(item => item.id === productForm.id)
      if (index !== -1) {
        Object.assign(productList.value[index], {
          ...productForm,
          updateTime: new Date().toISOString()
        })
      }
      ElMessage.success('产品更新成功')
    } else {
      // 新增产品
      const newProduct = {
        id: Date.now(),
        ...productForm,
        createTime: new Date().toISOString()
      }
      productList.value.unshift(newProduct)
      ElMessage.success('产品创建成功')
    }
    
    showProductDialog.value = false
    loadProductList()
  } catch (error) {
    console.error('提交失败:', error)
  } finally {
    submitting.value = false
  }
}

const resetProductForm = () => {
  Object.assign(productForm, {
    id: null,
    productName: '',
    marketPrice: null,
    originalPrice: null,
    currentPrice: null,
    productDescription: '',
    productImage: '',
    status: 1,
    isPromotion: false
  })
  if (productFormRef.value) {
    productFormRef.value.clearValidate()
  }
}

const beforeImageUpload = (file) => {
  const isJPG = file.type === 'image/jpeg'
  const isPNG = file.type === 'image/png'
  const isGIF = file.type === 'image/gif'
  const isWEBP = file.type === 'image/webp'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG && !isPNG && !isGIF && !isWEBP) {
    ElMessage.error('图片只能是 JPG/PNG/GIF/WEBP 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

const handleImageUpload = (options) => {
  const file = options.file
  const reader = new FileReader()
  reader.onload = (e) => {
    productForm.productImage = e.target.result
  }
  reader.readAsDataURL(file)
}

const loadProductList = () => {
  loading.value = true
  // 模拟API调用延迟
  setTimeout(() => {
    // 在实际项目中，这里应该是API调用
    let filteredList = [...productList.value]
    
    // 关键词搜索
    if (searchKeyword.value) {
      filteredList = filteredList.filter(item => 
        item.productName.includes(searchKeyword.value)
      )
    }
    
    // 状态筛选
    if (filterStatus.value !== '') {
      filteredList = filteredList.filter(item => item.status === parseInt(filterStatus.value))
    }
    
    // 类型筛选
    if (filterType.value !== '') {
      if (filterType.value === 'normal') {
        filteredList = filteredList.filter(item => !item.isPromotion)
      } else if (filterType.value === 'promotion') {
        filteredList = filteredList.filter(item => item.isPromotion)
      }
    }
    
    total.value = filteredList.length
    // 这里简化处理，实际应该后端分页
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    productList.value = filteredList.slice(start, end)
    
    loading.value = false
  }, 500)
}

onMounted(() => {
  loadProductList()
})
</script>

<style scoped>
.farmer-product-management {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f7fa;
}

/* 头部样式 */
.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  margin-left: 20px;
  margin-right: 20px;
  padding: 10px 0;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.add-btn, .promotion-btn {
  padding: 12px 24px;
  border-radius: 12px;
  font-weight: 600;
}

/* 筛选区域 */
.filter-section {
  margin-bottom: 24px;
  margin-left: 20px;
  margin-right: 20px;
}

.filter-card {
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.filter-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-left {
  display: flex;
  align-items: center;
}

/* 产品列表 */
.product-list-section {
  margin-bottom: 24px;
  margin-left: 20px;
  margin-right: 20px;
}

.product-list-card {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.list-title {
  font-size: 18px;
  font-weight: 600;
  color: #2d3748;
}

.list-count {
  color: #718096;
  font-size: 14px;
}

/* 表格样式 */
.product-image {
  border-radius: 8px;
}

.image-error {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #c0c4cc;
}

.product-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

.name-text {
  font-weight: 500;
}

.promotion-tag {
  font-size: 12px;
}

.price-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.normal-price {
  font-size: 16px;
  font-weight: 600;
  color: #e53e3e;
}

.original-price {
  font-size: 14px;
  color: #a0aec0;
  text-decoration: line-through;
}

.current-price {
  font-size: 16px;
  font-weight: 600;
  color: #e53e3e;
}

.discount-rate {
  font-size: 12px;
  color: #67c23a;
  background: #f0f9ff;
  padding: 2px 6px;
  border-radius: 4px;
  display: inline-block;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 8px;
}

/* 分页 */
.pagination-section {
  display: flex;
  justify-content: center;
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px solid #f0f0f0;
}

/* 对话框样式 */
.product-dialog {
  border-radius: 16px;
}

.product-form {
  padding: 20px 0;
}

.unit {
  margin-left: 8px;
  color: #718096;
}

.price-tips {
  margin-top: 8px;
}

/* 图片上传 */
.avatar-uploader {
  :deep(.el-upload) {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: all 0.3s;
  }
  
  :deep(.el-upload:hover) {
    border-color: #409eff;
  }
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
  line-height: 120px;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
  object-fit: cover;
  border-radius: 6px;
}

.upload-tips {
  margin-top: 8px;
  color: #909399;
  font-size: 12px;
  line-height: 1.4;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .farmer-product-management {
    padding: 16px;
  }
  
  .header-section {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }
  
  .filter-content {
    flex-direction: column;
    gap: 16px;
  }
  
  .filter-left {
    flex-direction: column;
    width: 100%;
    gap: 12px;
  }
  
  .filter-left .el-input,
  .filter-left .el-select {
    width: 100% !important;
    margin-left: 0 !important;
  }
  
  .filter-right {
    width: 100%;
    display: flex;
    gap: 12px;
  }
  
  .action-buttons {
    flex-direction: column;
    gap: 4px;
  }
}
</style>